//
//  LJPermissionUtil.m
//  LajinLive
//
//  Created by 刘洋 on 16/8/19.
//  Copyright © 2016年 lajin. All rights reserved.
//

#import "IGPermissionUtil.h"
#import <AssetsLibrary/AssetsLibrary.h>//相册的使用权库 iOSVersion < 8.0
#import <Photos/Photos.h>//相册的使用权库 iOSVersion > 8.0

#import <AddressBook/AddressBook.h>//通讯录的使用权限  iOSVersion < 9.0
#import <Contacts/Contacts.h>//通讯录的使用权限  iOSVersion > 9.0

@implementation IGPermissionUtil
+ (IGPhotoAuthorizationStatus)photoAuthorizationStatus
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        ALAuthorizationStatus status =[ALAssetsLibrary authorizationStatus];
        switch (status) {
            case ALAuthorizationStatusNotDetermined:
                return IGPhotoAuthorizationStatusNotDetermined;
                break;
            case ALAuthorizationStatusRestricted:
                return IGPhotoAuthorizationStatusRestricted;
                break;
            case ALAuthorizationStatusDenied:
                return IGPhotoAuthorizationStatusDenied;
                break;
            case ALAuthorizationStatusAuthorized:
                return IGPhotoAuthorizationStatusAuthorized;
                break;
                
            default:
                break;
        }
    } else {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        switch (status) {
            case PHAuthorizationStatusNotDetermined:
                return IGPhotoAuthorizationStatusNotDetermined;
                break;
            case PHAuthorizationStatusRestricted:
                return IGPhotoAuthorizationStatusRestricted;
                break;
            case PHAuthorizationStatusDenied:
                return IGPhotoAuthorizationStatusDenied;
                break;
            case ALAuthorizationStatusAuthorized:
                return IGPhotoAuthorizationStatusAuthorized;
                break;
                
            default:
                break;
        }
    }
    return IGPhotoAuthorizationStatusDenied;
}

+ (IGAddressBookAuthorizationStatus)addressAuthorizationStatus {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0) {
        ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
        switch (status) {
            case kABAuthorizationStatusNotDetermined:
                return IGAddressBookAuthorizationStatusNotDetermined;
                break;
            case kABAuthorizationStatusRestricted:
                return IGAddressBookAuthorizationStatusRestricted;
                break;
            case kABAuthorizationStatusDenied:
                return IGAddressBookAuthorizationStatusDenied;
                break;
            case kABAuthorizationStatusAuthorized:
                return IGAddressBookAuthorizationStatusAuthorized;
                break;
                
            default:
                break;
        }
    } else {
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        switch (status) {
            case CNAuthorizationStatusNotDetermined:
                return IGAddressBookAuthorizationStatusNotDetermined;
                break;
            case CNAuthorizationStatusRestricted:
                return IGAddressBookAuthorizationStatusRestricted;
                break;
            case CNAuthorizationStatusDenied:
                return IGAddressBookAuthorizationStatusDenied;
                break;
            case CNAuthorizationStatusAuthorized:
                return IGAddressBookAuthorizationStatusAuthorized;
                break;
                
            default:
                break;
        }
    }
    return IGAddressBookAuthorizationStatusDenied;
}

+ (void)requestPhotoAuthorization:(void(^)())successBlock failureBlock:(void(^)())failureBlock
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        [[[ALAssetsLibrary alloc] init] enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
            if (successBlock) {//请求成功
                successBlock();
            }
        } failureBlock:^(NSError *error) {//请求失败
            if (failureBlock) {
                failureBlock();
            }
        }];
    } else {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (PHAuthorizationStatusAuthorized == status) {//请求成功
                if (successBlock) {
                    successBlock();
                }
            } else {//请求失败
                if (failureBlock) {
                    failureBlock();
                }
            }
        }];
    }
}

+ (void)ig_showAlertViewWithPermissionsAlertType:(IGPermissionsAlertType)permissionsAlertType block:(nullable void(^)())block
{
    if (block) {
        block();
    }
    NSString *message = @"";
    switch (permissionsAlertType) {
        case IGPermissionsAlertTypePhoto:
            message = NSLocalizedString(@"Please Allow BOE iGallery to Visit Your Mobile Album in 'Setting-Privacy-Pictures'.", nil);
            break;
        case IGPermissionsAlertTypeVoice:
            message = NSLocalizedString(@"Please Allow BOE iGallery to Visit Your Microphone in 'Setting-Privacy-Microphone'.", nil);
            break;
        case IGPermissionsAlertTypeCamera:
            message = NSLocalizedString(@"Please Allow BOE iGallery to Visit Your Mobile Camera in 'Setting-Privacy-Camera'.", nil);
            break;
        case IGPermissionsAlertTypeAddressBook:
            message = NSLocalizedString(@"Please Allow BOE iGallery to Visit Your Mobile Contact List in 'Setting-Privacy-Contact List'.", nil);
            break;
        case IGPermissionsAlertTypeNetWorkSet:
            message = NSLocalizedString(@"Open 'WiFi & Cellular Mobile Data'", nil);
            break;
        default:
            break;
    }
    
//    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
     UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Notice", nil) message:message preferredStyle:UIAlertControllerStyleAlert];

    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
//        UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
        UIAlertAction *action0 = [UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            
        }];
        
        [alertVC addAction:action0];
    } else {
//        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
         UIAlertAction *action1 = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:NSLocalizedString(@"Go Setting", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if([[UIApplication sharedApplication] canOpenURL:url]) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            }
        }];
        
        [alertVC addAction:action1];
        [alertVC addAction:action2];
    }

    [UIViewController ig_presentViewController:alertVC animated:YES completion:nil];
}

+ (void)ig_showActionSheetWithCameraBlock:(nullable void(^)())cameraBlock photoBlock:(nullable void(^)())photoBlock {
    
    //是否有相册的权限
    IGPhotoAuthorizationStatus status = [IGPermissionUtil photoAuthorizationStatus];
    //是否有相机的权限
    AVAuthorizationStatus authStatusCamera = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (status == IGPhotoAuthorizationStatusNotDetermined) {
        [IGPermissionUtil requestPhotoAuthorization:^{
            if (authStatusCamera == AVAuthorizationStatusNotDetermined) {
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {
                        [IGPermissionUtil showActionSheetWithCameraBlock:cameraBlock photoBlock:photoBlock];
                    } else {
                        //弹出去设置的提示框
                        [IGPermissionUtil ig_showAlertViewWithPermissionsAlertType:IGPermissionsAlertTypeCamera block:nil];
                    }
                }];
            }
        } failureBlock:^ {
            [IGPermissionUtil ig_showAlertViewWithPermissionsAlertType:IGPermissionsAlertTypePhoto block:nil];
        }];
        return;
    } else if (status == IGPhotoAuthorizationStatusDenied) {
        [IGPermissionUtil ig_showAlertViewWithPermissionsAlertType:IGPermissionsAlertTypePhoto block:nil];
        return;
    }

    if (authStatusCamera == AVAuthorizationStatusRestricted || authStatusCamera == AVAuthorizationStatusDenied)
    {//获取摄像头失败
        //弹出去设置的提示框
        [IGPermissionUtil ig_showAlertViewWithPermissionsAlertType:IGPermissionsAlertTypeCamera block:nil];
        return;
    } else if (authStatusCamera == AVAuthorizationStatusNotDetermined) {//还没有对应用进行授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                [IGPermissionUtil showActionSheetWithCameraBlock:cameraBlock photoBlock:photoBlock];
            } else {
                //弹出去设置的提示框
                [IGPermissionUtil ig_showAlertViewWithPermissionsAlertType:IGPermissionsAlertTypeCamera block:nil];
            }
        }];
        return;
    }
    
    [IGPermissionUtil showActionSheetWithCameraBlock:cameraBlock photoBlock:photoBlock];
}

+ (void)showActionSheetWithCameraBlock:(nullable void(^)())cameraBlock photoBlock:(nullable void(^)())photoBlock {
    UIAlertController *actionSheetVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action0 = [UIAlertAction actionWithTitle:NSLocalizedString(@"Camera", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (cameraBlock) {
            cameraBlock();
        }
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:NSLocalizedString(@"Select from Album", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (photoBlock) {
            photoBlock();
        }
    }];
//    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action)
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [actionSheetVC addAction:action0];
    [actionSheetVC addAction:action1];
    [actionSheetVC addAction:action2];
    [UIViewController ig_presentViewController:actionSheetVC animated:YES completion:nil];
}

+ (BOOL)isAllPermissionsOpen
{
    AVAuthorizationStatus authStatusCamera = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    AVAudioSessionRecordPermission authStatusVoice = [[AVAudioSession sharedInstance] recordPermission];
    IGPhotoAuthorizationStatus authStatusPhoto = [IGPermissionUtil photoAuthorizationStatus];
    
    if (authStatusCamera == AVAuthorizationStatusAuthorized && authStatusVoice == AVAudioSessionRecordPermissionGranted && authStatusPhoto == IGPhotoAuthorizationStatusAuthorized) {
        return YES;
    }
    
    return NO;
}

+ (void)requestAddressBookAuthorization:(nullable void(^)())successBlock failureBlock:(nullable void(^)())failureBlock {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 9.0) {
        
        ABAddressBookRef addressRef = ABAddressBookCreateWithOptions(nil, nil);
        
        //注册通讯录更新回调
        ABAddressBookRequestAccessWithCompletion(addressRef, ^(bool granted, CFErrorRef error) {
            if (granted) {
                // 授权成功
                if (successBlock) {
                    successBlock();
                }
            }else{
                // 授权失败
                if (failureBlock) {
                    failureBlock();
                }
            }
        });
    } else {
        CNContactStore * store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {// 授权成功
                if (successBlock) {
                    successBlock();
                }
            }else{ // 授权失败
                if (failureBlock) {
                    failureBlock();
                }
            }
        }];
            
    }
}

@end
